<template>
  <div>
    <div class="naming-title">
      <div style="margin-right: 2em">
        素材命名规则
      </div>
      {{ titleList.join('-') }}
    </div>
    <div class="naming-body">
      <!--类型列-->
      <div style="padding-top: 1em;height:auto;overflow: scroll">
        <div v-for="(item,index) in typeList" :key="index" class="type_style" @click="chooseType(item)"
             :class="(theType != null && theType.name === item.name)? 'type_choose':''">
          <div style=" width: 160px;text-overflow: ellipsis; overflow: hidden; white-space: nowrap;" :title="item.name">{{ item.name }}</div>
          <i v-if="(theType != null && theType.name === item.name) === item.name" class="el-icon-arrow-right"></i>
        </div>
      </div>
      <!--标签组列-->
      <div style="margin-left: 2em;height:auto;overflow: scroll">
        <div v-for="(item,index) in groupList" :key="index" class="group_style">
          <div class="tags_radio" @click="handleSelectGroup(item,index)" v-if="((item.type == 'system' && item.code != 'shortId') || (item.tags != null && item.tags.length > 0))"
               :style="{background:item.groupFlag != 0?'#34C758':''}"></div>
          <div class="tags_radio_disabled" v-else
               :style="{background:item.groupFlag != 0?'#b3b3b3':''}"></div>
          <div class="group_box" @click="chooseGroup(item)" style=" width: 160px;text-overflow: ellipsis; overflow: hidden; white-space: nowrap;" :title="item.name" :style="item.code == 'shortId'?'border: 2px solid rgba(232, 232, 232, 100);':''">
            {{ item.name }}
          </div>
          <i v-if="item.type != 'system' && (item.groupFlag != 0 || (theGroup != null && theGroup.name === item.name))" class="el-icon-arrow-right"></i>
        </div>
      </div>

      <!--标签列-->
      <div style="margin-left: 1em;height:auto;overflow: scroll">
        <div v-for="(item,index) in labelList" :key="index" class="tags_style">
          <div class="tags_radio" @click="handleSelectTag(item,index)"
               :style="{background:item.tagsFlag == 1?'#34C758':''}"></div>
          <div class="tags_box">
            <div style="width: 150px;border-right: 1px solid #e8e8e8 ; margin-right: 5px; text-overflow: ellipsis; overflow: hidden; white-space: nowrap;" :title="item.name">{{ item.name }}</div>
            <div class="tags_radio" @click="handleSelectNameFlag(item,index)"
                 :style="{background:item.flag == 1?'#34C758':''}"></div>
            <div>生成素材名</div>
          </div>
        </div>
      </div>
    </div>
    <div style="width: 100%;display: flex;justify-content: center">
      <el-button size="small" @click="save">保存</el-button>
      <el-button size="small" @click="cancelDialog">取消</el-button>
    </div>
  </div>
</template>

<script>
import tags from '@/util/tags';
import {getSystemTags, getTenantTags} from '@/api/system/creative_tags';
import {deepClone,findArray, findByProp, findObject} from '@/util/util';
import Vue from "vue";

export default {
  name: "creativeNameRule",
  props: {
    dataList: {
      type: Object
    },
    modelIndex: String,
    cancel: Function,
    addTags: Function
  },
  data() {
    return {
      titleList: [],
      typeList: [],
      groupList: [],
      labelList: [],
      theType: null,
      theGroup: null,
      nextSelectedSeq: 1,
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    modelTagsToTenantTags(modelTags) {
      let resultTags = [];
      if(modelTags != null) {
        modelTags.forEach(modelTag=>{
          let typeTag = findObject(resultTags,modelTag.tagType.name,'name');
          if(typeTag == null) {
            typeTag = {
              name: modelTag.tagType.name,
              type: modelTag.tagType.type,
              groups: [],
            };
            resultTags.push(typeTag);
            let group = {
              name: modelTag.name,
              type: modelTag.type,
              code: modelTag.code,
              tags: modelTag.tags,
            };
            typeTag.groups.push(group);
          }
        });
      }
      return resultTags;
    },
    init() {
      //获取标签列表
      Promise.all([
        getSystemTags(),
        getTenantTags()
      ]).then((result) => {
        if (result) {
          /*
          * 主要思想：用一个变量nextSelectedSeq里跟踪标签组的选择顺序，每选中一次，将标签组的groupFlag设置为nextSelectedSeq，同时nextSelectedSeq增加1，取消选中，则将标签组groupFlag设置为0.
          * 在typeList中，groupFlag不为0的标签组即为选择的标签组，groupFlag按从小到大排序，即标签组选择的顺序。
          */
          let oldModelTags = [];
          if(this.dataList.tagsSnapshot != null) {
            oldModelTags = JSON.parse(JSON.stringify(this.dataList.tagsSnapshot));
          }
          this.typeList = tags.tagsAdd(tags.tagsAdd(result[0].data.data, result[1].data.data),this.modelTagsToTenantTags(oldModelTags));
          this.typeList.forEach(theType=>{
            if(theType.groups != null) {
              theType.groups.forEach(theGroup=>{
                theGroup.groupFlag = 0;
                if (theGroup.code === "shortId"){
                  theGroup.groupFlag = 1;
                }
                if(theGroup.tags != null) {
                  theGroup.tags.forEach(tag=>{
                    tag.flag = 0;
                    tag.tagsFlag = 0;
                  })
                }
              });
            }
          });
          oldModelTags.forEach(modelGroup=>{
            let theType = findObject(this.typeList,modelGroup.tagType.name,'name');
            let theGroup = findObject(theType.groups,modelGroup.name,'name');
            theGroup.groupFlag = this.nextSelectedSeq;
            this.nextSelectedSeq ++;
            if(modelGroup.tags != null && theGroup.tags != null) {
              modelGroup.tags.forEach(tag=>{
                let theTag = findObject(theGroup.tags,tag.name,'name');
                if(theTag != null) {
                  theTag.tagsFlag = 1;
                  theTag.flag = tag.flag;
                }
              });
            }
          });
          if(this.typeList.length > 0) {
            this.chooseType(this.typeList[0])
          }
          this.updateTitle();
        }
      })
    },
    cancelDialog() {
      this.cancel()
    },
    //选择类型
    chooseType(type) {
      this.theType = type;
      this.groupList = (type == null || type.groups == null)?[]:type.groups;
      this.theGroup = (this.groupList.length > 0)?this.groupList[0]:null;
      this.chooseGroup(this.theGroup);
    },
    //选择组
    chooseGroup(group) {
      this.theGroup = group;
      this.labelList = (group == null || group.tags == null)?[]:group.tags;
    },
    handleSelectGroup(group, i) {
      if(group.groupFlag == 0) {
        group.groupFlag = this.nextSelectedSeq;
        this.nextSelectedSeq ++;
      } else {
        group.groupFlag = 0;
      }
      if(group.tags != null) {
        group.tags.forEach(tag=>{
          if(group.groupFlag == 0) {
            tag.tagsFlag = 0;
            tag.flag = 0;
          } else {
            tag.tagsFlag = 1;
          }
        });
      }
      this.$set(this.theType.groups,findArray(this.theType.groups,group.name,'name'),{
        ...group
      })
      this.chooseGroup(group);
      this.updateTitle();
    },
    handleSelectTag(v, i) {
      let flag = v.tagsFlag === 0 ? 1 : 0;
      v.tagsFlag = flag;
      if (flag === 0) {
        v.flag = 0
      }
      this.$set(this.labelList,i,{
        ...v
      })
      this.tagsChangeGroup()
    },
    handleSelectNameFlag(v, i) {
      console.log(v);
      let flag = v.flag === 0 ? 1 : 0;
      v.flag = flag;
      if (flag === 1) {
        v.tagsFlag = 1
      }
      this.$set(this.labelList,i,{
        ...v
      })
      this.tagsChangeGroup()
    },
    //点击标签修改组的状态
    tagsChangeGroup() {
      let theGroup = this.theGroup;
      let isSelectedGroup = 0;
      theGroup.tags.forEach(tag=>{
        if(tag.tagsFlag != 0) {
          isSelectedGroup = 1;
        }
      });
      let groupUpdated = false;
      if(isSelectedGroup == 1 && theGroup.groupFlag == 0) {
        theGroup.groupFlag = this.nextSelectedSeq;
        this.nextSelectedSeq ++;
        groupUpdated = true;
      }
      if(isSelectedGroup == 0 && theGroup.groupFlag != 0) {
        theGroup.groupFlag = 0;
        groupUpdated = true;
      }
      if(groupUpdated) {
        this.$set(this.theType.groups,findArray(this.theType.groups,theGroup.name,'name'),{
          ...theGroup
        })
      }
      this.updateTitle();
    },
    updateTitle() {
      let titleGroupList = [];
      this.typeList.forEach(theType=>{
        if(theType.groups != null) {
          theType.groups.forEach(theGroup=>{
            if(theGroup.groupFlag != 0) {
              let nameEnable = false;
              if(theGroup.type == 'system') {
                nameEnable = true;
              } else if(theGroup.tags != null) {
                theGroup.tags.forEach(tag=>{
                  if(tag.flag == 1) {
                    nameEnable = true;
                  }
                })
              }
              if(nameEnable) {
                titleGroupList.push({
                  name: theGroup.name,
                  groupFlag: theGroup.groupFlag,
                });
              }
            }
          })
        }
      })
      titleGroupList.sort((a,b)=>{
        return (a.groupFlag - b.groupFlag);
      })
      let titleList = [];
      titleGroupList.forEach(titleGroup=>{
        titleList.push(titleGroup.name);
      });
      this.titleList = titleList;
    },
    collectModelTags() {
      let modelTags = [];
      let typeList = deepClone(this.typeList);
      typeList.forEach(theType=>{
        if(theType.groups != null) {
          theType.groups.forEach(theGroup=>{
            if(theGroup.groupFlag != 0) {
              let newGroup = {...theGroup};
              modelTags.push(newGroup);
              newGroup.tagType = {
                name: theType.name,
                type: theType.type,
                code: theType.code,
              };
              if(theGroup.tags != null) {
                newGroup.tags = [];
                theGroup.tags.forEach(tag=>{
                  if(tag.tagsFlag == 1) {
                    let newTag = {
                      ...tag,
                    };
                    delete newTag.tagsFlag;
                    newGroup.tags.push(newTag);
                  }
                });
              }
            }
          });
        }
      });
      modelTags.sort((a,b)=>{
        return a.groupFlag - b.groupFlag;
      })
      modelTags.forEach(theGroup=>{
        delete theGroup.groupFlag;
      });
      return modelTags;
    },
    //保存
    save() {
      let modelTags = this.collectModelTags();
      this.addTags(this.modelIndex, modelTags)
    }
  }
}
</script>

<style scoped lang="scss">
.naming-title {
  display: flex;
}

.naming-body {
  height: 60vh;
  margin-top: 4em;
  display: flex;
}

.type_style {
  display: flex;
  cursor: pointer;
  margin-bottom: 1em;
  font-size: 16px;

  i {
    font-size: 19px;
    line-height: 25px;
  }

  &:hover {
    color: #00a2ff;
    font-weight: 600;
  }
}

.type_choose {
  font-size: 15px;
  color: #00a2ff;
  font-weight: 600;
}

.group_style {
  display: flex;
  cursor: pointer;
  margin-bottom: 1em;
  font-size: 14px;
  align-items: center;

  i {
    font-size: 19px;
    line-height: 25px;
  }

  .group_box {
    width: 200px;
    border: 2px solid rgba(232, 232, 232, 100);
    padding: 6px 11px;
    border-radius: 8px;
    margin-right: 3em;
  }

  &:hover {
    .group_box {
      border: 2px solid #00a2ff;
    }

    i {
      color: #00a2ff;
    }
  }
}

.tags_style {
  display: flex;
  cursor: pointer;
  margin-bottom: 1em;
  font-size: 13px;
  align-items: center;

  i {
    font-size: 19px;
    line-height: 25px;
  }

  .tags_box {
    display: flex;
    border: 2px solid rgba(232, 232, 232, 100);
    padding: 6px 11px;
    border-radius: 8px;
    margin-right: 3em;
  }

  &:hover {
    .group_box {
      border: 2px solid #00a2ff;
    }

    i {
      color: #00a2ff;
    }
  }
}

.tags_radio {
  width: 18px;
  height: 18px;
  margin-right: 1em;
  border-radius: 50%;
  border: 1px solid rgba(187, 187, 187, 100);
}
.tags_radio_disabled {
  width: 18px;
  height: 18px;
  margin-right: 1em;
  border-radius: 50%;
  border: 1px solid rgba(187, 187, 187, 100);
  background: #b3b3b3;
}
</style>
